package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    /**
     * 发表评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 判断内容是否大于140字
        if (dto == null || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 判断用户是否登录(要求使用手机号和密码登录的用户)
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return
                    ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 安全过滤--阿里云文本审核
        boolean security = securityFiltering(dto.getContent());
        if (security == false) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
            ApComment comment = new ApComment();
            comment.setAuthorId(user.getUserId());
            // 根据用户id查询用户,调用用户微服务提供的远程接口
            ResponseResult<ApUser> userById = userFeign.getUserById(user.getUserId());
            if (userById.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApUser apUser = userById.getData();
                comment.setAuthorName(apUser.getName());
                comment.setImage(apUser.getImage());
            }
            comment.setEntryId(dto.getArticleId());
            comment.setChannelId(dto.getChannelId());
            comment.setType(0);
            comment.setContent(dto.getContent());
            comment.setLikes(0);
            comment.setReply(0);
            comment.setFlag(0);
            comment.setCreatedTime(new Date());
            mongoTemplate.save(comment);
        System.out.println(comment);
            return ResponseResult.okResult();
        }

    /**
     * 评论点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //判断用户是否登录
        User user = MediaThreadLocalUtil.get();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //创建点赞数据
        ApCommentLike like=new ApCommentLike();
        like.setAuthorId(user.getUserId());
        like.setCommentId(dto.getCommentId());
        like.setOperation(dto.getOperation());
        //判断用户是否已经对这篇评论有过点赞记录
        Query query=new Query();
        //查询用户id
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        //查询评论id
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        //用manggodb经行查询
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        //如果查询不到数据
        if (one==null){
            //新增点赞数据
            mongoTemplate.save(like);
            //更新评论表点赞数量+1
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
            Update update=new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(query1,update,ApComment.class);
        }else {
            //如果取消点赞,改为1
            if (one.getOperation() !=dto.getOperation()){
                int add= 1;
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                //点赞 0
                if (dto.getOperation()==1){
                    add=-1;
                }
                Query query1 = new Query();
                query1.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
                Update update=new Update();
                update.inc("likes",add);
                mongoTemplate.updateFirst(query1,update,ApComment.class);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 评论列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
            dto.setSize(10);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        // 分页 和 排序
        Pageable page = PageRequest.of(0, dto.getSize(), Sort.Direction.DESC, "createdTime");
        query.with(page);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        // 判断当前用户是否登录
        User user = MediaThreadLocalUtil.get();
        List<ApCommentLike> likes = new ArrayList<>();
        // 登录用户需要查看当前返回的列表中是否已经有点赞记录
        if (user != null) {
            List<String> commentIds = new ArrayList<>();
            for (ApComment apComment : apComments) {
                commentIds.add(apComment.getId());
            }
            Query likeQuery = new Query();
            likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            likeQuery.addCriteria(Criteria.where("commentId").in(commentIds));
            likeQuery.addCriteria(Criteria.where("operation").is(0));
            likes = mongoTemplate.find(likeQuery, ApCommentLike.class);
        }
        List<String> existCommentIds = new ArrayList<>();
        for (ApCommentLike like : likes) {
            existCommentIds.add(like.getCommentId());
        }
        // 返回vo对象集合
        List<ApCommentVo> vos = new ArrayList<>();
        for (ApComment apComment : apComments) {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(apComment, vo);
            // 默认没有点赞,设置为1
            vo.setOperation(1);
            if (existCommentIds.contains(apComment.getId())) {
                vo.setOperation(0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }

    /**
     * 安全过滤,阿里云文字审核
     * @param content
     * @return
     */
    private boolean securityFiltering(String content) {
        boolean result=false;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "pass":
                    result=true;
                    break;
                case "block":
                    result=false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
